import { LockOutlined, MobileOutlined } from "@ant-design/icons";
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from "@ant-design/pro-components";
import { useMutation } from "@apollo/client";
import { Tabs, message, theme } from "antd";
import { SEND_CODE_MSG, LOGIN } from "@/graphql/auth";
import styles from "./index.module.less";
import { AUTH_TOKEN } from "@/utils/constants";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useTitle } from "@/hooks";
import { useUserContext } from "@/hooks/userHooks";

interface IValues {
  tel: string;
  code: string;
  autoLogin: boolean;
}
const Page = () => {
  const { token } = theme.useToken();
  const [run] = useMutation(SEND_CODE_MSG);
  const [login] = useMutation(LOGIN);
  const [params] = useSearchParams();
  const nav = useNavigate();
  const { store } = useUserContext();
  useTitle("登录");
  const loginHandler = async (values: IValues) => {
    const res = await login({
      variables: values,
    });
    if (res.data?.login.code === 200) {
      // 登录成功后刷新用户信息
      store.refetchHandler();
      if (values.autoLogin) {
        sessionStorage.setItem(AUTH_TOKEN, "");
        localStorage.setItem(AUTH_TOKEN, res.data?.login.data);
      } else {
        localStorage.setItem(AUTH_TOKEN, "");
        sessionStorage.setItem(AUTH_TOKEN, res.data?.login.data);
      }
      message.success("登录成功");
      nav(params.get("originUrl") || "/");
      return;
    } else {
      message.error(res.data?.login.message);
    }
  };
  return (
    <div className={styles.container}>
      <LoginFormPage
        initialValues={{ tel: "18232079049" }}
        onFinish={loginHandler}
        backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
        logo="https://zc-water-drop-assets.oss-cn-beijing.aliyuncs.com/images/avatar.jpg"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="keep"
        containerStyle={{
          backgroundColor: "rgba(0, 0, 0,0.65)",
          backdropFilter: "blur(4px)",
        }}
        subTitle="React18"
      >
        <Tabs centered items={[{ key: "phone", label: "手机号登录" }]} />
        <>
          <ProFormText
            fieldProps={{
              size: "large",
              prefix: (
                <MobileOutlined
                  style={{
                    color: token.colorText,
                  }}
                  className={"prefixIcon"}
                />
              ),
            }}
            name="tel"
            placeholder={"手机号"}
            rules={[
              {
                required: true,
                message: "请输入手机号！",
              },
              {
                pattern: /^1\d{10}$/,
                message: "手机号格式错误！",
              },
            ]}
          />
          <ProFormCaptcha
            fieldProps={{
              size: "large",
              prefix: (
                <LockOutlined
                  style={{
                    color: token.colorText,
                  }}
                  className={"prefixIcon"}
                />
              ),
            }}
            captchaProps={{
              size: "large",
            }}
            placeholder={"请输入验证码"}
            captchaTextRender={(timing, count) => {
              if (timing) {
                return `${count} ${"获取验证码"}`;
              }
              return "获取验证码";
            }}
            name="code"
            phoneName="tel"
            rules={[
              {
                required: true,
                message: "请输入验证码！",
              },
            ]}
            onGetCaptcha={async (tel: string) => {
              const res = await run({
                variables: {
                  tel,
                },
              });
              if (res.data?.sendCodeMsg.code === 200) {
                message.success("获取验证码成功！");
              } else {
                message.error(res.data?.sendCodeMsg.message);
              }
            }}
          />
        </>
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a
            style={{
              float: "right",
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider dark>
      <Page />
    </ProConfigProvider>
  );
};
